package lc.q101_150;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Q131 {
    public List<List<String>> partition(String s) {
        int length = s.length();
        boolean[][] dp = new boolean[length][length];
        for (int i = 0; i < length; i++) {
            Arrays.fill(dp[i], true);
        }
        // 判断i, j是否为回文
        for (int i = length - 1; i >= 0; --i) {
            for (int j = i + 1; j < length; j++) {
                dp[i][j] = s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1];
            }
        }
        // 深度下探所有的
        ArrayList<List<String>> lists = new ArrayList<>();
        dfs(s, 0, dp, lists, new ArrayList<String>());
        return lists;
    }

    private void dfs(String s, int i, boolean[][] dp, ArrayList<List<String>> lists, ArrayList<String> strings) {
        if (i == s.length()) {
            lists.add(new ArrayList<>(strings));
            return;
        }
        for (int j = i; j < s.length(); j++) {
            if (dp[i][j]) {
                strings.add(s.substring(i, j + 1));
                dfs(s, j + 1, dp, lists, strings);
                strings.remove(strings.size() - 1);
            }
        }
    }


}
